<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px defect-form" label-width="68">
      <el-row :gutter="20">
        <el-col :span="4.8">
          <el-form-item label="版本" prop="projectVersionId">
            <el-select v-model="queryParams.projectVersionId" filterable clearable remote :loading="selectLoading"
              :remote-method="remoteMethod" placeholder="请选择版本">
              <el-option v-for="item in versionList" :key="item.id" :label="item.versionName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="报告人" prop="creator">
            <el-select v-model="queryParams.creator" filterable clearable placeholder="请选择报告员">
              <el-option v-for="item in memberList" :key="item.memberName" :label="item.memberName"
                :value="item.memberId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="缺陷等级" prop="bugLevel">
            <el-select v-model="queryParams.bugLevel" filterable clearable placeholder="请选择严重级别">
              <el-option v-for="item in getIntDictOptions(DICT_TYPE.BUG_LEVEL)" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="提测版本" prop="requestFormId">
            <el-select v-model="queryParams.requestFormId" filterable clearable placeholder="请选择提测版本">
              <el-option v-for="item in commitList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="用例集" prop="testPlanCasesId">
            <el-tree-select v-model="queryParams.testPlanCasesId" :data="testPlanCasesList" check-strictly
              :props="{ label: 'name', value: 'id' }" filterable clearable node-key="id" placeholder="请选择测试用例集"
              :render-after-expand="false" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="4.8">
          <el-form-item label="ID" prop="id">
            <el-input v-model="queryParams.id" clearable placeholder="请输入缺陷ID" />
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="指派人" prop="developer">
            <el-select v-model="queryParams.developer" filterable clearable placeholder="请选择指派人">
              <el-option v-for="item in memberList" :key="item.memberName" :label="item.memberName"
                :value="item.memberId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="缺陷类型" prop="bugType">
            <el-select v-model="queryParams.bugType" filterable clearable placeholder="请选择缺陷类型">
              <el-option v-for="item in bugTypeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="测试环境" prop="environment">
            <el-input v-model="queryParams.environment" clearable placeholder="请输入测试环境" />
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="优先级" prop="bugPriority">
            <el-select v-model="queryParams.bugPriority" filterable clearable placeholder="请选择优先级">
              <el-option v-for="item in getIntDictOptions(DICT_TYPE.PRIORITY)" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="4.8">
          <el-form-item label="缺陷状态" prop="bugStatus1">
            <el-select v-model="queryParams.bugStatus1" filterable clearable multiple placeholder="请选择缺陷状态">
              <el-option v-for="item in getIntDictOptions(DICT_TYPE.BUG_STATUS)" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="隐藏状态" prop="hideStatus1">
            <el-select v-model="queryParams.hideStatus1" filterable clearable multiple placeholder="请选择隐藏状态">
              <el-option v-for="item in getIntDictOptions(DICT_TYPE.BUG_STATUS)" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="描述内容" prop="description">
            <el-input v-model="queryParams.description" clearable placeholder="请输入描述" />
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="报告日期" prop="createTime">
            <el-date-picker v-model="queryParams.createTime"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" end-placeholder="结束日期"
              start-placeholder="开始日期" type="daterange" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item style="padding: 0 0 0 0px;margin-right: 0px;" class="query">
            <el-button @click="handleQuery" >
              <Icon class="mr-5px" icon="ep:search" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon class="mr-5px" icon="ep:refresh" />
              重置
            </el-button>
            <el-button plain type="primary" @click="updateForm('create')" v-if="addPermission"
              v-hasPermi="['bug:bug-info:create']">
              <Icon class="mr-5px" icon="ep:plus" />
              新增
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :show-overflow-tooltip="true">
      <el-table-column align="center" label="ID" prop="id" />
      <el-table-column align="center" label="提测版本" prop="requestFormId" width="150">
        <template #default="scope">
          {{ findVersionName(scope.row.requestFormId) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="描述" prop="description" width="500" />
      <el-table-column align="center" label="状态" prop="bugStatus" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BUG_STATUS" :value="scope.row.bugStatus" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="指派人" prop="developer" />
      <el-table-column align="center" label="缺陷类型" prop="bugType">
        <template #default="scope">
          {{ findBugTypeName(scope.row.bugType) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="严重级别" prop="bugLevel">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BUG_LEVEL" :value="scope.row.bugLevel" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="优先级" prop="bugPriority">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PRIORITY" :value="scope.row.bugPriority" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="更新时间" prop="updateTime" :formatter="dateFormatter" />
      <el-table-column align="center" label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="updateForm('update', scope.row)" v-if="updatePermission"
            v-hasPermi="['bug:bug-info:update']">
            编辑
          </el-button>
          <el-button link type="primary" @click="updateForm('view', scope.row)" v-if="updatePermission"
            v-hasPermi="['bug:bug-info:update']">
            详情
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-if="delPermission"
            v-hasPermi="['bug:bug-info:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="page">
      <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo" :total="total"
        @pagination="getList" />
    </div>
    <!-- 表单弹窗：添加/修改 -->
    <UpdateForm ref="formRef" @success="getList" />
  </ContentWrap>
</template>
<script lang="ts" setup>
defineOptions({ name: 'DefectManage' })
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as DefectApi from '@/api/defect'
import UpdateForm from './UpdateForm.vue'
import { getProjectMemberList } from '@/api/project'
import { dateFormatter } from '@/utils/formatTime'
import { getDemandList, getProjectMemberRole } from '@/api/demand'
import { useAppStore } from '@/store/modules/app'
import { getTestboxTree, getTestformList } from '@/api/usecase'
const { currentRoute } = useRouter()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const appStore = useAppStore()
const projectId = computed(() => appStore.getSelectProject)
const loading = ref(false) // 列表的加载中
const list = ref([] as any) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  id: '',
  projectVersionId: '',
  creator: '',
  developer: '',
  updater: '',
  bugType: '',
  bugLevel: '',
  bugStatus1: [],
  hideStatus1: [],
  bugStatus: '',
  hideStatus: '',
  bugPriority: '',
  requestFormId: '',
  createTime: '',
  description: '',
  testPlanCasesId: '',
  environment: '',
  projectId: projectId.value
})
const queryFormRef = ref() // 搜索的表单
const total = ref(0) // 列表的总页数
const memberList = ref([] as any) // 用户列表
const versionList = ref([] as any) // 版本列表
const commitList = ref([] as any) // 测试计划
const testPlanCasesList = ref([] as any) // 测试用例集
const { path,query } = unref(currentRoute)
const role = ref('')
const bugTypeList = ref([] as any)
const selectLoading = ref(false)
const addPermission = computed(() => ['admin', 'testManager', 'tester'].includes(role.value))
const delPermission = computed(() => ['admin', 'testManager', 'tester'].includes(role.value))
const updatePermission = computed(() =>
  ['admin', 'projectManager', 'developer', 'testManager', 'tester'].includes(role.value)
)

watch(
  () => projectId.value,
  async () => {
    queryParams.projectId = projectId.value
    getTestPlanCasesList()
    await getCommitList()
    // getVersion()
    getMembers()
    getList()
    getProjectMemberRoleFn()
  }
)
watch(
  () => query.bugId,
  async () => {
    queryParams.id = query.bugId as any
    nextTick(()=>{
      if (projectId.value) {
        getList()
      }
    })
  },
  {
    immediate:true
  }
)
onUpdated(() => {
  if (projectId.value) {
    getCommitList()
  }
})
// 获取问题类型
const getBugType = () => {
  const list = getIntDictOptions(DICT_TYPE.BUG_TYPE)
  bugTypeList.value = list
}

// 通过问题类型value 获取label
const findBugTypeName = (type) => {
  return bugTypeList.value.find((b) => b.value == type).label
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  list.value = []
  try {
    const data = await DefectApi.getDefectList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  queryParams.bugStatus = queryParams.bugStatus1.join(',')
  queryParams.hideStatus = queryParams.hideStatus1.join(',')
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.id = ''
  handleQuery()
}

/** 添加修改操作 */
const formRef = ref()
const updateForm = (type: string, row?: object) => {
  formRef.value.open(type, row)
}

// 删除操作
const handleDelete = async (id) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DefectApi.deleteDefect({ id })
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}
// 获取成员列表
const getMembers = async () => {
  let data = await getProjectMemberList({
    pageNo: 1,
    pageSize: 100,
    projectId: projectId.value
  })
  memberList.value = data
}

const remoteMethod = async (query: string) => {
  if (query) {
    selectLoading.value = true
    try {
      getVersion(query)
    } finally {
      selectLoading.value = false
    }
  } else {
    getVersion()
  }
}
// 获取版本列表
const getVersion = async (query) => {
  let data = await getDemandList({
    pageNo: 1,
    pageSize: 100,
    versionName: query,
    projectId: projectId.value
  })
  versionList.value = data.list
}
// 获取提测单
const getCommitList = async () => {
  loading.value = true
  commitList.value = []
  try {
    let data = await getTestformList({
      projectId: projectId.value
    })
    commitList.value = data.map((item) => {
      return {
        label: `${item.version.versionName}版本-${item.rounds}轮次`,
        value: item.id
      }
    })
  } finally {
    loading.value = false
  }
}

// 获取人员在项目中角色
const getProjectMemberRoleFn = async () => {
  let data = await getProjectMemberRole({ projectId: projectId.value })
  role.value = data
}
// 获取版本名称
const findVersionName = (id) => {
  if (!id) return ''
  let temp = commitList.value.find((v) => v.value == id)
  return temp ? temp.label : ''
}
// 获取测试用例集
const getTestPlanCasesList = async () => {
  let data = await getTestboxTree({ projectId: projectId.value })
  testPlanCasesList.value = data ? [data] : []
}
/** 初始化 **/
onMounted(async () => {
  getBugType()
  if (projectId.value) {
    queryParams.projectId = projectId.value
    getTestPlanCasesList()
    getMembers()
    // getVersion()
    await getCommitList()
    getList()
    getProjectMemberRoleFn()
  }
})
</script>
<style lang="scss">
.file-wrap {
  max-height: 300px;
  overflow: auto;
}

.el-form--inline .el-form-item {
  margin-right: 20px;
}

.defect-form {
  .query{
    >div{
      display: flex;
      flex-wrap: nowrap;
    }
  }
  .el-row {
    .el-col {
      flex: 1;

      .el-form-item {
        width: 100%;
      }

      .el-date-editor.el-input,
      .el-date-editor.el-input__wrapper {
        width: auto;
      }
    }
  }
}
</style>
